package main

import (
	"context"
	"demo/micro/grpc/etcdclient"
	"errors"
	"github.com/coreos/etcd/mvcc/mvccpb"
	"go.etcd.io/etcd/clientv3"
)

var (
	cli2 *clientv3.Client
)

//服务发现，返回地址列表
func Discover(serviceName string, etcdAddr string) (addrs []string, err error) {
	serviceName = "/grpc/" + serviceName
	if cli2 == nil {
		cli2, err = etcdclient.EtcdInit(etcdAddr)
		if err != nil {
			return nil, err
		}
	}
	resp, err := cli2.Get(context.Background(), serviceName, clientv3.WithPrefix())
	if err != nil {
		return nil, err
	}

	if resp.Count == 0 {
		return nil, errors.New("service list empty")
	}

	addrs = make([]string, resp.Count, resp.Count)
	for i, kv := range resp.Kvs {
		addrs[i] = string(kv.Value)
	}

	return addrs, nil
}

func Watch(c *grpcClient, serviceName string) {
	serviceName = "/grpc/" + serviceName

	//观察事件
	watchChan := cli2.Watch(context.Background(), serviceName, clientv3.WithPrefix())

	go func() {
		for n := range watchChan {
			for _, ev := range n.Events {
				value := string(ev.Kv.Value)
				eventType := ev.Type

				switch eventType {
				case mvccpb.PUT:
					c.AddClient(value)
				case mvccpb.DELETE:
					c.DeleteClient(value)
				}
			}
		}
	}()
}
